package com.model;

import com.alibaba.druid.pool.DruidDataSource;
import com.exception.ApiException;

import java.sql.SQLException;

/**
 * @author: cxt
 * @time: 2022/6/23
 * <p>
 * 数据源的一个封装组合，方便后续操作多源情况
 */
public class DataBaseSource {
    /**
     * 配置信息
     */
    protected DataInfo dataInfo;

    /**
     * 数据源
     */
    protected DruidDataSource dataSource;

    /**
     * 标记是否关闭，默认 false
     */
    private volatile Boolean isClosed = false;

    /**
     * 是否初始化完成
     */
    private volatile Boolean initialization = false;

    /**
     * 是否出错
     */
    private volatile Boolean isError = false;

    private final Object lock = new Object();

    public DataBaseSource(DataInfo dataInfo, DruidDataSource dataSource) {
        this.dataInfo = dataInfo;
        this.dataSource = dataSource;
    }

    /**
     * 初始化数据
     */
    public void init() {
        if (!isClosed) {
            if (!initialization) {
                synchronized (lock) {
                    try {
                        dataSource.init();
                        initialization = true;
                    } catch (SQLException e) {
                        isError = true;
                        e.printStackTrace();
                        throw new ApiException("初始化连接异常", e.getMessage());
                    }
                }
            }
        }
    }

    /**
     * 关闭连接
     */
    public void close() {
        dataSource.close();
        isClosed = true;
    }

    public DataInfo getDataInfo() {
        return dataInfo;
    }

    public DruidDataSource getDataSource() {
        return dataSource;
    }

    public Boolean getClosed() {
        return isClosed;
    }

    public Boolean getInitialization() {
        return initialization;
    }

    public Boolean getError() {
        return isError;
    }
}
